//
//  SNDBConn.m
//  ShaoNianGong
//
//  Created by zyt on 15-8-19.
//  Copyright (c) 2015年 zyt. All rights reserved.
//

#define DBMainThreadCheck() NSAssert([NSThread mainThread] == NO,  \
@"The query DB action in main thread is too slow,which may block main thread")

#import "DBDatabaseConn.h"

#if FMDB_SQLITE_STANDALONE
#import <sqlite3/sqlite3.h>
#else
#import <sqlite3.h>
#endif
#import <pthread.h>

@interface DBDatabaseConn (){
    pthread_mutex_t _dbLock;
    FMDatabaseQueue *_databaseQueue;
    FMDatabaseQueue *_wordsDatabaseQueue;
}

@end

@implementation DBDatabaseConn

singleton_implementation(DBDatabaseConn)

- (instancetype)init{
    self = [super init];
    if (self) {
         pthread_mutex_init(&_dbLock, NULL);
        
        [[NSNotificationCenter defaultCenter]
         addObserver:self
         selector:@selector(receiveMemoryWarning)
         name:UIApplicationDidReceiveMemoryWarningNotification
         object:nil];
    }
    return self;
}

- (void)dealloc{
    pthread_mutex_destroy(&_dbLock);
}

- (void)receiveMemoryWarning{
    pthread_mutex_lock(&_dbLock);
    _databaseQueue = nil;
    _wordsDatabaseQueue = nil;
    pthread_mutex_unlock(&_dbLock);
}

#pragma mark - ......::::::: public :::::::......

+ (NSString*)dbSecret {
    return @"ZeQge2zCbBkSvd69gMk2i7ZeQge2zCbBkSvd69gMk2i7";
}

- (pthread_mutex_t*) dbLock {
    return &_dbLock;
}

#pragma mark - ......::::::: public :::::::......

- (FMDatabaseQueue *)databaseQueue {
    pthread_mutex_lock(&_dbLock);
    if (_databaseQueue == nil) {
        _databaseQueue = [FMDatabaseQueue databaseQueueWithPath:_emojiDBFilePath flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE];
    }
    pthread_mutex_unlock(&_dbLock);
    return _databaseQueue;
}

@end
